import { ElMessage } from "element-plus";
import startIcon from "/@/assets/source/start-icon.png";
import endIcon from "/@/assets/source/end-icon.png";

// 获取点是否在面内 传入经纬度对象及对比面
export const getComputedArea = (point: number[], path: number[][]) => {
  if (path.length == 0) return true;
  const isPointInRing = path.some((item) => {
    return window.AMap.GeometryUtil.isPointInRing(point, item);
  });
  return isPointInRing;
};
// 获取面与面的相交关系
export const getComputedAreaIntersect = (polygon2: any, allMapPolygon: any) => {
  if (!allMapPolygon) return false;
  const polygon1_path = allMapPolygon.getPath()[1];
  const polygon2_path = polygon2.getPath();
  // 两圈是否交叉
  const doesRingRingIntersect = window.AMap.GeometryUtil.doesRingRingIntersect(
    polygon2_path,
    polygon1_path,
  );
  return doesRingRingIntersect;
};

// 绘制marker https://lbs.amap.com/api/javascript-api-v2/documentation#marker
// 只是绘制marker，不添加到地图上
export function drawMarker(data: {
  position: Required<number[]>;
  icon?: string;
  size?: number[];
  content?: string | HTMLElement;
  title?: string;
  visible?: boolean;
  zIndex?: number;
  offset?: number[];
  anchor?:
    | "top-left"
    | "top-center"
    | "top-right"
    | "middle-left"
    | "center"
    | "middle-right"
    | "bottom-left"
    | "bottom-center"
    | "bottom-right";
  angle?: number;
  clickable?: boolean;
  draggable?: boolean;
  bubble?: boolean;
  zooms?: number[];
  cursor?: "pointer";
  topWhenClick?: boolean;
  height?: number;
  label?: {
    content: string;
    offset: number[];
    direction: "top" | "right" | "bottom" | "left" | "center";
  };
  extData?: Record<string, any>;
}) {
  const params = Object.assign(
    {
      visible: true,
      zIndex: 12,
      offset: [0, 0],
      angle: 0,
      clickable: true,
      draggable: false,
      bubble: false,
      zooms: [2, 20],
      cursor: "pointer",
      topWhenClick: false,
      height: 0,
    },
    data,
  );
  if (params.icon && params.size) {
    params.icon = new window.AMap.Icon({
      size: new window.AMap.Size(params.size[0], params.size[1]), // 图标尺寸
      image: params.icon, // 图标的取图地址
      imageSize: new window.AMap.Size(params.size[0], params.size[1]), // 图片尺寸
    });
  }
  const marker = new window.AMap.Marker(params);
  return marker;
}

// 绘制line
export function drawRoute(
  map: any,
  route: number[][],
  color = "#56bb97",
  showDir = false,
  isFiteView = true,
  strokeStyle: "solid" | "dashed" = "solid",
  bweight: number = 2,
  opacity: number = 0.9,
  sweight: number = 5,
  lineJoin: string = "round",
) {
  const routeLine = new window.AMap.Polyline({
    path: route,
    isOutline: true,
    outlineColor: "#ffeeee",
    borderWeight: bweight,
    strokeWeight: sweight,
    strokeOpacity: opacity,
    strokeColor: color,
    strokeStyle,
    lineJoin: lineJoin,
    showDir,
  });
  console.log("routeLine", routeLine);
  map.add(routeLine);

  // 调整视野达到最佳显示区域
  if (isFiteView) map.setFitView([routeLine]);

  return routeLine;
}

//MeshLine 线

export function drawRouteMeshLine(map: any, route: number[][], color = "#56bb97") {
  console.log("drawRouteMeshLine", color);
  var bezierCurve = new window.AMap.BezierCurve({
    path: route, //曲线路径
    strokeWeight: 2, //线条宽度
    strokeColor: "#fff", //线条颜色
    isOutline: true, //是否描边
    outlineColor: "red", //描边颜色
    borderWeight: 1, //描边宽度
  });

  map.add(bezierCurve);

  return bezierCurve;
}
// function computeBezier(points: any, numberOfPoints: any) {
// 	var dt;
// 	var i;
// 	var curve = [];

// 	dt = 1.0 / (numberOfPoints - 1);

// 	for (i = 0; i < numberOfPoints; i++) {
// 		curve[i] = pointOnCubicBezier(points, i * dt);
// 	}

// 	return curve;
// }
// function pointOnCubicBezier(cp: any, t: any) {
// 	var ax, bx, cx;
// 	var ay, by, cy;
// 	var tSquared, tCubed;

// 	cx = 3.0 * (cp[1].lng - cp[0].lng);
// 	bx = 3.0 * (cp[2].lng - cp[1].lng) - cx;
// 	ax = cp[3].lng - cp[0].lng - cx - bx;

// 	cy = 3.0 * (cp[1].lat - cp[0].lat);
// 	by = 3.0 * (cp[2].lat - cp[1].lat) - cy;
// 	ay = cp[3].lat - cp[0].lat - cy - by;

// 	tSquared = t * t;
// 	tCubed = tSquared * t;

// 	var lng = ax * tCubed + bx * tSquared + cx * t + cp[0].lng;
// 	var lat = ay * tCubed + by * tSquared + cy * t + cp[0].lat;

// 	return new window.AMap.LngLat(lng, lat);
// }
// function getEllipseHeight(count: any, maxHeight: any, minHeight: any) {
// 	var height = [];
// 	var radionUnit = Math.PI / 180;

// 	for (var i = 0; i < count; i++) {
// 		var radion = i * radionUnit;

// 		height.push(minHeight + Math.sin(radion) * maxHeight);
// 	}

// 	return height;
// }
// 绘制多边形
interface DrawPolygonInterface {
  path: number[][]; // 路径
  strokeColor?: string; // 边框色
  strokeStyle?: "solid" | "dashed"; // 边框类型
  strokeWeight?: number; // 边框粗细
  strokeOpacity?: number; // 边框透明度
  fillColor?: string; // 填充颜色
  fillOpacity?: number; // 填充色透明度
  zIndex?: number;
  isFiteView?: boolean;
}
export function drawPolygon(map: any, data: DrawPolygonInterface) {
  data = Object.assign(
    {
      path: [],
      strokeColor: "#55B8FF",
      strokeStyle: "solid",
      strokeWeight: 6,
      strokeOpacity: 1,
      fillColor: "#8FC3FF",
      fillOpacity: 0.4,
      zIndex: 10,
      isFiteView: true,
    },
    data,
  );

  const polygon = new window.AMap.Polygon({
    path: data.path,
    strokeColor: data.strokeColor,
    strokeWeight: data.strokeWeight,
    strokeOpacity: data.strokeOpacity,
    strokeStyle: data.strokeStyle,
    fillOpacity: data.fillOpacity,
    fillColor: data.fillColor,
    zIndex: data.zIndex,
  });

  map.add(polygon);
  if (data.isFiteView) map.setFitView();
  return polygon;
}

// 绘制圆
interface DrawCircleInterface {
  center: number[]; // 中心点
  radius: number; // 半径
  strokeColor?: string; // 边框颜色
  strokeStyle?: "solid" | "dashed"; // 边框线类型
  strokeOpacity?: number; // 边框透明度
  strokeWeight?: number; // 边框粗细
  strokeDasharray?: number[]; // 边框虚线间距
  fillColor?: string; // 填充色
  fillOpacity?: number; // 填充色透明度
  zIndex?: number;
  isFiteView?: boolean;
}
export function drawCircle(map: any, data: DrawCircleInterface) {
  data = Object.assign(
    {
      center: [],
      radius: 10,
      strokeColor: "#55B8FF",
      strokeStyle: "solid",
      strokeWeight: 6,
      strokeOpacity: 1,
      strokeDasharray: [10, 10],
      fillColor: "#8FC3FF",
      fillOpacity: 0.4,
      zIndex: 10,
      isFiteView: true,
    },
    data,
  );

  const circle = new window.AMap.Circle({
    center: data.center,
    radius: data.radius,
    strokeColor: data.strokeColor,
    strokeOpacity: data.strokeOpacity,
    strokeWeight: data.strokeWeight,
    strokeStyle: data.strokeStyle,
    strokeDasharray: data.strokeDasharray,
    fillColor: data.fillColor,
    fillOpacity: data.fillOpacity,
    zIndex: data.zIndex,
  });

  map.add(circle);
  if (data.isFiteView) map.setFitView();
  return circle;
}

// 绘制聚合点
export function drawMarkerCluster(
  map: any,
  point: { lnglat: Required<number[]>; weight?: number; [key: string]: any }[],
  options: {
    gridSize?: number;
    maxZoom?: number;
    averageCenter?: boolean;
    clusterByZoomChange?: boolean;
    styles?: {
      url: string;
      size: number;
      offset: number[];
      imageOffset: number[];
      textColor?: string;
      textSize?: number;
    };
    renderClusterMarker?: (e: { count: number; clusterData: any[]; marker: any }) => void;
    renderMarker?: (e: { data: any[]; marker: any }) => void;
  },
) {
  const params = Object.assign(
    {
      gridSize: 60,
      maxZoom: 16,
      averageCenter: true,
      clusterByZoomChange: false,
    },
    options,
  );
  const markerCluster = new window.AMap.MarkerCluster(map, point, params);

  return markerCluster;
}

// 获取经纬度
export function getLatLon(address: string) {
  if (address === undefined) {
    throw new Error("getLatLon参数错误address:" + address);
  }

  return new Promise<any>((resolve, reject) => {
    //回调函数
    try {
      const geocoder = new window.AMap.Geocoder({});
      geocoder.getLocation(address, (status: string, result: any) => {
        if (status === "complete" && result.info === "OK") {
          const geocodes = result.geocodes;
          resolve(geocodes);
        } else {
          reject();
          ElMessage.error("地址解析失败");
        }

        reject("getLatLon解析失败->status:" + status + ", result:" + result);
      });
    } catch (error) {
      reject(error);
    }
  });
}
/**
 * 获取坐标
 * @param longitude 经度
 * @param latitude 纬度
 * @returns
 */
export function getAddress(longitude: number, latitude: number) {
  if (longitude === undefined || latitude === undefined) {
    throw new Error("getAddress参数错误longitude:" + longitude + ", latitude:" + latitude);
  }

  /**
   * Extract
   */
  return new Promise<{
    longitude: number;
    latitude: number;
    formattedAddress: string; // 详细地址
    addressComponent: {
      adcode: string; // 行政区划代码
      city: string; // 城市
      citycode: string; // 城市编码
      district: string; // 区
      province: string; // 省
      street: string; // 街道
      streetNumber: string; // 门牌号
      towncode: string; // 乡镇编码
      township: string; // 乡镇
    };
  }>((resolve, reject) => {
    //回调函数
    const geocoder = new window.AMap.Geocoder({});
    geocoder.getAddress([longitude, latitude], (status: any, result: any) => {
      if (status === "complete" && result.info === "OK") {
        const regeocode = result.regeocode;
        resolve({ ...regeocode, longitude, latitude });
      }

      reject("getAddress解析失败->status:" + status + ", result:" + result);
    });
  });
}

// POI搜索
export function searchPoi(keyword = "") {
  const placeSearch = new window.AMap.PlaceSearch({
    city: "成都",
    pageSize: 20, // 单页显示结果条数
    pageIndex: 1, // 页码
  });

  return new Promise<any[]>((resolve, reject) => {
    placeSearch.search(keyword, function (status: string, result: any) {
      // 查询成功时，result即对应匹配的POI信息
      if (status === "complete") {
        if (result.info !== "OK") reject(status + ":" + result.info);

        resolve(result.poiList.pois);
      } else {
        reject(status);
      }
    });
  });
}

// 根据线数据，将文字绘制到线中间
export function drawLineTextCenter(map: any, geom: number[][], text: string, color: string) {
  function getArrayCenterEl(data: number[][]) {
    if (data.length == 0) return [];
    return data[Math.round(data.length / 2)];
  }
  function createCircleLineMarker(data: any, color: string) {
    const marker = new window.AMap.Marker({
      anchor: "top-center",
    });
    marker.setContent(
      `<div class="circle-marker-poline-line" style="color:${color};width:80px;">
			<span>${data.name}</span>
    	</div> `,
    );
    marker.setPosition(data.position);
    return marker;
  }
  const geomCenter = getArrayCenterEl(geom);
  const point = createCircleLineMarker(
    {
      name: text,
      position: geomCenter
        ? new window.AMap.LngLat(geomCenter[0], geomCenter[1])
        : new window.AMap.LngLat(0, 0),
    },
    color,
  );
  map.add(point);
  return point;
}
// 获取路线图
export function getRouteLine(start: string, end: string, policy: string) {
  return new Promise((resolve, reject) => {
    new window.AMap.Driving({
      city: "成都",
      policy,
    }).search(
      [
        { keyword: start, city: "成都" },
        { keyword: end, city: "成都" },
      ],
      function (status: string, result: object) {
        if (status === "complete") {
          resolve(result);
        } else {
          reject(status);
        }
      },
    );
  });
}
// 绘制货车地图路线
export function drawDriveLine(routes: any[], map: object, activeIndex: number) {
  // new window.AMap.Polyline.setPath([])
  // console.log(routes, "iiiiiiiiiii")
  routes &&
    routes.length &&
    routes.forEach((route: { steps: any[] }, index) => {
      const { steps = [] } = route;

      const pathArr = steps.map((i) => {
        return i.path;
      });
      const path = flatten(pathArr); //通过合并数组的方法，得到所有点的集合

      // 绘制轨迹，利用折线类方法进行渲染
      new window.AMap.Polyline({
        map,
        path,
        showDir: true,
        // strokeColor: "#459c50",
        strokeColor: activeIndex == index ? "#459c50" : "#9ac799", // 线颜色，这里颜色做了判断，让当前选中的线路颜色比没有选中的颜色深一些，类似于高德的地图路线推荐
        strokeOpacity: 1, // 线透明度
        strokeWeight: 10, // 线宽
        strokeStyle: "solid", // 线样式
        lineJoin: "round", // 折线拐点的绘制样式
        zIndex: activeIndex == index ? 999 : 200,
        // zIndex: 999
      });

      function flatten(arr: any) {
        // 合并多个数组
        const result = [];
        for (let i = 0; i < arr.length; i++) {
          for (let j = 0; j < arr[i].length; j++) {
            result.push(arr[i][j]);
          }
        }
        return result;
      }

      // 添加起始标记
      const startMarker = new window.AMap.Marker({
        position: path[0], // 起点位置
        // content: '<div class="marker-label-font">始</div>', // 显示文字
        icon: new window.AMap.Icon({
          image: startIcon,
          size: new window.AMap.Size(32, 32),
          imageSize: new window.AMap.Size(32, 32),
        }),
        offset: new window.AMap.Pixel(-10, -20), // 调整偏移量，使标记更好地显示
      });

      // 添加终点标记
      const endMarker = new window.AMap.Marker({
        position: path[path.length - 1], // 终点位置
        // content: '<div class="marker-label-font">终</div>', // 显示文字
        icon: new window.AMap.Icon({
          image: endIcon,
          size: new window.AMap.Size(32, 32),
          imageSize: new window.AMap.Size(32, 32),
        }),
        offset: new window.AMap.Pixel(-10, -20), // 调整偏移量
      });

      // 将标记添加到地图
      startMarker.setMap(map);
      endMarker.setMap(map);
    });
}
